<?php
namespace Shop\Controller;
use Think\Controller;
use User\Api\UserApi;
class MemberController extends ShopController {
    public function __construct(){
      parent::__construct(); 
		$this->card = M("membercard");$this->consum = M("shop_consum");

    }
    public function lists(){ 
		$map = "type_id=".$this->type_id;
		$mobile = trim($_POST['mobile']);
		if($mobile){
			$map .= " AND (cardnum LIKE '%$mobile%' OR mobile LIKE '%$mobile%')";
			$this->assign('mobile',$mobile);
		}
		
		$rows = $_GET['rows'] ? $_GET['rows'] : 10;
		$count      = $this->card->where($map)->count();
		$Page       = new \Think\Page($count,$rows);  
		$show = $Page->show();
        $list = $this->card->where($map)->limit($Page->firstRow.','.$Page->listRows)->select();

		if(!empty($list))
		{
           foreach($list as $key=>$val)
		   {
			  $maps['shop_id'] = $this->shop_id; 
			  $maps['card_id'] = $val['id']; 
			  $maps['flag'] = 2; 
              $list[$key]['consum'] = $this->consum->where($maps)->sum('money'); unset($maps);
		   }
		}

        $this->assign("list",$list);
		$this->assign("page",$show);
        $this->display();
    }
	//会员卡认证
	public function openAuth(){
		$id = intval($_POST['id']);
		if($id>0)
		{ 
			M("membercard")->where(array('id'=>$id))->save(array('flag'=>1));
			echo '<font color="red">已认证</font>';
		}
	}
	//会员卡导出
	// public function daochu(){
 //        $map['type_id'] = $this->type_id; 

	// 	$mobile = trim($_REQUEST['mobile']);

	// 	if($mobile)
	// 	{
 //           $map['mobile'] = $mobile;
		  
	// 	}
 //        $list = $this->card->where($map)->order("add_time desc")->select();
 //        Vendor('PHPE.PHPExcel','','.php');


	// 	$excel = new \PHPExcel();
 //      //Excel表格式,这里简略写了8列
 //        $letter = array('A','B','C','D','E','F','F','G','H','I');
 //        //表头数组
	
 //        $tableheader = array('序号','持卡人','领卡时间','手机号','积分','消费','余额');
 //        //填充表头信息
 //        for($i = 0;$i < count($tableheader);$i++) {
 //            $excel->getActiveSheet()->setCellValue("$letter[$i]1","$tableheader[$i]");
 //        }
 //        //表格数组
	// 	$data = array();
	//     if(!empty($list))
	// 	{
	// 		foreach($list as $key=>$val)
	// 		{
	// 			$data[$key]['id'] = $val['id'];
	// 			$data[$key]['name'] = $val['name'];
	// 			$data[$key]['add_time'] = date('Y-m-d H:i:s',$val['add_time']);
	// 			$data[$key]['mobile'] = $val['mobile'];
	// 			$data[$key]['point'] = $val['point'];
				
	// 			//$maps['shop_id'] = $this->shop_id; 
	// 		    $maps['card_id'] = $val['id'];
	// 			$maps['flag'] = 2; 
 //                $data[$key]['deadtime'] = $this->consum->where($maps)->sum('money'); unset($maps);
	// 			$data[$key]['money'] = $val['money'];
	// 		}
	// 	}
 //        //填充表格信息
 //        for ($i = 2;$i <= count($data) + 1;$i++) {
 //            $j = 0;
 //            foreach ($data[$i - 2] as $key=>$value) {
 //                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
 //                $j++;
 //            }
 //        }
 //        //创建Excel输入对象
 //        $write = new \PHPExcel_Writer_Excel5($excel);
 //        header("Pragma: public");
 //        header("Expires: 0");
 //        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
 //        header("Content-Type:application/force-download");
 //        header("Content-Type:application/vnd.ms-execl");
 //        header("Content-Type:application/octet-stream");
 //        header("Content-Type:application/download");;
 //        header('Content-Disposition:attachment;filename="会员卡信息'.date("Y-m-d H:i:s",time()).'.xls"');
 //        header("Content-Transfer-Encoding:binary");
 //        $write->save('php://output');
 //    }
	// 消费（充值）记录导出
	public function daochu_record(){
		$id = $_REQUEST['id'];
		// if($id < 1) errorTip("会员卡不存在");
		$map = array(
			'sid' => $this->shop_static_info['sid'],
			'tid' => $this->shop_static_info['type_id'],
			);
		if(!empty($id)) $map['cid'] = $id;
		if(!empty($_GET['starttime']) && !empty($_GET['endtime'])){
			$map['e_time'] = array('between',strtotime($_GET['starttime']).",".strtotime($_GET['endtime']));
		}else if(!empty($_GET['starttime'])){
			$map['e_time'] = array('gt',strtotime($_GET['starttime']));
		}

		$list = M('expenselog')->where($map)->order("e_time DESC")->select();

		Vendor('PHPE.PHPExcel','','.php');
		$excel = new \PHPExcel();
		$letter = array('A','B','C','D','E','F','F','G','H','I','J');
		$tableheader = array('交易单号','会员手机号','交易金额','赠送金额','获得积分','交易类型','交易时间','备注','交易余额');
		// $title = 

		// 填充表头信息
        for($i = 0;$i < count($tableheader);$i++) {
            $excel->getActiveSheet()->setCellValue($letter[$i]."1",$tableheader[$i]);
        }

        // 组装表格内容
        $data = array();
        foreach($list as $v){
        	// $data[] = array(
        	// 	'ordernum' => $v['ordernum'],
        	// 	'mobile'   => $v['mobile'],
        	// 	'money'    => $v['money'],
        	// 	'giving'   => $v['giving'],
        	// 	'e_point'  => $v['e_point'],
        	// 	'type'     => $v['e_type']? '消费':'充值',
        	// 	'time'     => time_format($v['e_time']),
        	// 	'note'     => $v['note'],
        	// 	'balance'  => $v['balance']
        	// 	);
        	$data[] = array($v['ordernum'],$v['mobile'],$v['money'],$v['giving'],$v['e_point'],$v['e_type']? '消费':'充值',time_format($v['e_time']),$v['note'],$v['balance']);
        }
        // 填充表格内容
     //    for($i=2;$i<count($data);$i++){
     //    	for($j=0;$j<count($date[0]);$j++){
     //    		if($i===1){
     //    			// 写表头
     //    			$excel->getActiveSheet()->setCellValue($letter[$j].$i,$tableheader[$j]);
     //    		}else{
     //    			// 写内容
					// $excel->getActiveSheet()->setCellValue($letter[$j].$i,$data[$i-2][$j]);
     //    		}
     //    	}
     //    }
        for ($i = 2;$i <= count($data) + 1;$i++) {
            $j = 0;
            foreach ($data[$i - 2] as $key=>$value) {
                $excel->getActiveSheet()->setCellValue("$letter[$j]$i","$value");
                $j++;
            }
        }

        //创建Excel输入对象
        $write = new \PHPExcel_Writer_Excel5($excel);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");;
        header('Content-Disposition:attachment;filename="账单流水.xls"');
        header("Content-Transfer-Encoding:binary");
        $write->save('php://output');

    }
	//编辑会员卡页面
	public function edit(){
		if(IS_POST)
		{
		  //extract($_POST);
          $data = $_POST;
		  $id = $data['id'];
		  unset($data['id']);
		  M("membercard")->where(array('id'=>$id))->save($data);
		  successTip("修改成功!",'?s=Member/lists');
		}else
		{ 
			$id = intval($_GET['id']);
		   if($id)
			{
			   $rs = M("membercard")->where(array('id'=>$id))->find(); //print_R($rs);
			   if($rs['type_id']==$this->type_id)
				{
                  $this->assign("data",$rs);	
				}else
				{
					errorTip("会员信息不存在！");
				}
			}
		   $this->display();
		}
	}
	//充值页面
	public function paycheck(){
		$id = intval($_GET['id']);
		if($id>0)
		{
			$rs = M("membercard")->where(array('id'=>$id))->find();
			if($rs['id']>0)
			{
              if($rs['type_id']==$this->type_id)
				{

				  $this->assign("name",$rs['name']);
				  $this->assign("mobile",$rs['mobile']);
                  $this->assign("id",$id);	
				}else
				{
					errorTip("会员信息不存在！");
				}
			}else{
			   errorTip("会员信息不存在！");
			}
            
		}
		$this->display();
	}
		//消费页面
	public function consume(){
		$id = intval($_GET['id']);
		if($id>0)
		{
			$rs = M("membercard")->where(array('id'=>$id))->find();
			if($rs['id']>0)
			{
              if($rs['type_id']==$this->type_id)
				{
				  $where = array('c.shop_id'=>$this->shop_static_info['sid'],'uid'=>$rs['uid'],'one_coupon_data.status'=>0,'c.endtime'=>array('gt',NOW_TIME));
				  $field = "one_coupon_data.id as pid,one_coupon_data.times as surplus,c.title,c.type,c.imgurl,c.dikou,c.jianmian";

				  $coupons = M('coupon_data')->join("RIGHT JOIN one_coupon c on one_coupon_data.coupon_id=c.id")->where($where)->field($field)->select();
				  if(!$coupons) $coupons = array();
				  $this->assign("coupons",$coupons);
				  $this->assign("name",$rs['name']);
				  $this->assign("mobile",$rs['mobile']);
                  $this->assign("id",$id);	
				}else
				{
					errorTip("会员信息不存在！");
				}
			}else{
			   errorTip("会员信息不存在！");
			}
            
		}
		$this->display();
	}
	public function getCard(){
      $mobile = $_POST['mobile'];
	  
	  if($mobile)
		{
          $rs = M("membercard")->where(array('mobile'=>$mobile,'type_id'=>$this->type_id))->find();
		  if($rs['id']>0)
			{
			  $rs['money'] = $rs['money'] ? $rs['money'] : '0.00';
			  $rs['point'] = $rs['point'] ? $rs['point'] : 0;
		       $str = '<p style="margin-top:3px;color:red;">持卡人： '.$rs['name'].'</p><p style="margin-top:3px;color:red;">余额:  ¥'.$rs['money'].'</p><p style="margin-top:3px;color:red;">积分:  '.$rs['point'].'</p>';
			}else
			{
		       $str = '<p style="margin-top:3px;color:red;">该手机号会员不存在哦！</p>';
			}
			echo $str;exit;
		}
	
	}
	//充值
	public function recharge(){ 
			$status['error'] = 1 ;
			// $status['msg'] = json_encode($_POST);
			// $this->ajaxReturn($status);
			$id = intval($_POST['cid']);

			// 判断会员卡有效性
			$card_info = M('membercard')->find($id);
			if(!$card_info){
			  $status['msg'] = '会员信息不存在';
              $this->ajaxReturn($status);
			}

			// 开启事务 进行逻辑操作
			M()->startTrans();

			// 判断消费类型，进行区别处理
			if($_POST['e_type']){
				// 消费
				if($_POST['total'] != $_POST['money'] + $_POST['giving']){
					// 消费金额不对
					$status['msg'] = '消费金额有误';
              		$this->ajaxReturn($status);
				}
				if($_POST['paytype'] == 0 && $card_info['money'] < $_POST['money']){
					// 使用余额支付时余额不足
					$status['msg'] = '卡内余额不足';
              		$this->ajaxReturn($status);
				}

				// 判断是否使用优惠券
				if(!empty($_POST['coupon']) && $_POST['coupon'] > 0){
					// 使用优惠券
					$field = "one_coupon_data.times as surplus,c.endtime,c.title,c.type,c.imgurl,c.dikou,c.jianmian";
				    $coupon_info = M('coupon_data')->join("RIGHT JOIN one_coupon c on one_coupon_data.coupon_id=c.id")->where("one_coupon_data.id=".$_POST['coupon'])->field($field)->find();
				    if($coupon_info['endtime'] < NOW_TIME){
				    	$status['msg'] = '优惠券已过期';
              			$this->ajaxReturn($status);
				    }

				    // 判断优惠券类型
				    if($coupon_info['type'] == 1){
				    	// 体验券
				    	if($coupon_info['surplus'] < 1){
				    		$status['msg'] = '体验次数已经使用完';
              				$this->ajaxReturn($status);
				    	}elseif($coupon_info['surplus'] == 1){
				    		$couponsave = array('status'=>1,'sumtime'=>NOW_TIME,'times'=>0);
				    	}else{
				    		$couponsave = array('sumtime'=>NOW_TIME,'times'=>array('exp',"times-1"));
				    	}
				    }elseif($coupon_info['type'] == 2){
				    	// 代金券
				    	if($_POST['total'] < $coupon_info['jianmian'] || $_POST['giving'] > $coupon_info['dikou']){
				    		$status['msg'] = '代金券使用出错';
              				$this->ajaxReturn($status);
				    	}
				    	$couponsave = array('sumtime'=>NOW_TIME,'status'=>1);
				    }
				    $coupon_rs = M('coupon_data')->where("id=".$_POST['coupon'])->save($couponsave);
				}else{
					// 不使用优惠券
					$coupon_rs = true;
				}
				// 计算会员卡余额
				if($_POST['paytype'] == 0){
					$card['money'] = $card_info['money'] - $_POST['money'];
				}else{
					$card['money'] = $card_info['money'];
				}
			}else{
				$coupon_rs = true;
				// 充值
				$card['money'] = $card_info['money'] + $_POST['money'] + $_POST['giving'];
				$card['point'] = $card_info['point'] + $_POST['e_point'];
			}

			
			// 组装数据
			// $data = $_POST;
			$data = array(
				'ordernum' => date("Ymdhis").rand(1000,9999),
				'sid'      => $this->shop_static_info['sid'],
				'tid'      => $this->shop_static_info['type_id'],
				'uid'      => $this->shop_static_info['uid'],
				'pid'      => empty($_POST['coupon'])? 0:$_POST['coupon'],
				'cid'      => $id,
				'cnum'	   => $card_info['cartid'],
				'mobile'   => $card_info['mobile'],
				'money'    => $_POST['money'],
				'giving'   => $_POST['giving'],
				'e_point'  => $_POST['e_point'],
				'e_type'   => $_POST['e_type'],
				'is_cash'  => $_POST['paytype'],
				'e_time'   => NOW_TIME,
				'balance'  => $card['money'],
				'note'     => $_POST['note']
				);
			// $data = array_merge($data,$_POST);

			// 写入消费日志表
			$log = M('expenselog')->add($data);

			// 更改会员卡余额信息
			if(($_POST['paytype'] == 0 || $_POST['e_type'] == 0)&& $coupon_info['type'] != 1){
				$cardchange = M('membercard')->where("id=$id")->save($card);
			}else{
				$cardchange = true;
			}
			
				// M()->rollback();
				// $status['msg'] = json_encode(array("log"=>$log,"cardchange"=>$cardchange,"Coupon_rs"=>$coupon_rs));
				// $this->ajaxReturn($status);
			if($log && $cardchange && $coupon_rs){
				// 数据库写入无误， 提交事务
				M()->commit();
				$status['error'] = 0;
				$status['msg'] = '操作成功！余额：'.$card['money'];
			}else{
				// 数据写入异常 回滚事务
				M()->rollback();
				$status['msg'] = '操作失败！'.M()->getError();
			}
			$this->ajaxReturn($status);		

    }

	//删除会员卡
	public function DelAll(){
			$ids = $_REQUEST['id'];

			
			if(!empty($ids))
		    {
			   $map['id'] = array('in',$ids);
			  $this->card->where($map)->delete();	
			}
			$this->success('操作成功！', U('lists'));
    }

	//账单流水
	public function bill(){
		$id = $_REQUEST['id'];
		// if($id < 1) errorTip("会员卡不存在");
		$map = array(
			'sid' => $this->shop_static_info['sid'],
			'tid' => $this->shop_static_info['type_id'],
			);
		if(!empty($id)) $map['cid'] = $id;
		if(!empty($_GET['starttime']) && !empty($_GET['endtime'])){
			$map['e_time'] = array('between',strtotime($_GET['starttime']).",".strtotime($_GET['endtime']));
			$datechose = array('starttime'=>$_GET['starttime'],'endtime'=>$_GET['endtime']);
		}else if(!empty($_GET['starttime'])){
			$map['e_time'] = array('gt',strtotime($_GET['starttime']));
			$datechose = array('starttime'=>$_GET['starttime'],'endtime'=>"结束时间");
		}else{
			$datechose = array('starttime'=>"开始时间",'endtime'=>"结束时间");
		}

		$rows = $_GET['rows'] ? $_GET['rows'] : 10;
		$count = M('expenselog')->where($map)->count();
		$page = new \Think\Page($count,$rows);
		$show = $page->show();

		$list = M('expenselog')->where($map)->order("e_time DESC")->limit($Page->firstRow.','.$Page->listRows)->select();
		$list = is_array($list)? $list : array();

		// 统计数据 总充值，赠送
		$map['e_type'] = '0';
		$statistics = M('expenselog')->where($map)->field("sum(money) as money,sum(giving) as giving")->find();
		$map['e_type'] = "1";
		$statistics['xiaofei'] = M('expenselog')->where($map)->sum('money');

		$this->assign("id",$id);
		$this->assign("list",$list);
		$this->assign("statistics",$statistics);
		$this->assign("page",$Page);
		$this->assign("datechose",$datechose);
        $this->display();
	}
				//删除记录
	public function delsum(){
			$id = $_REQUEST['id'];
			if($id>0){
			  $map['id'] =  $id;
               $this->consum->where($map)->delete();	
			}
			$this->success('操作成功！', U('lists'));
    }
	//店铺数据统计
	public function tongji(){
       $this->display();
    }
}
?>